<template>
  <div>
    <el-card shadow="never" class="margin-30" :body-style="{ padding: '20px' }">
      <div slot="header">
        <span>{{ headtitle }}</span>
      </div>
      <!-- card body -->
      <el-form ref="articleForm" :model="article" :rules="rules" label-width="120px" :inline="false" size="medium">
        <el-row :gutter="20">
          <el-col :span="7" :offset="0">
            <el-form-item prop="author" label="作者">
              <el-input v-model="article.author" placeholder="作者" />
            </el-form-item>
          </el-col>
          <el-col :span="7" :offset="0">
            <el-form-item prop="title" label="标题">
              <el-input v-model="article.title" />
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="2">
            <el-form-item prop="isShow" label="是否显示">
              <el-switch v-model="article.isShow" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="15" :offset="0">
            <el-form-item prop="summary" label="摘要">
              <el-input v-model="article.summary" type="textarea" :rows="3" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8" :offset="0">
            <el-form-item prop="coverImg" label="封面图片">
              <el-upload ref="coverImgUplaod" :action="uploadFileOss" clear-files :headers="token" :show-file-list="false"
                :on-success="handleCoverImgSucc" :before-upload="beforeAvatarUpload">
                <img v-if="article.coverImg" width="100" height="100" :src="article.coverImg">
                <el-button v-else size="small" type="primary">点击上传素材</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过1.5MB</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="切换富文本类型">
              <!-- editorType (integer, optional): 编辑器类型: 0 富文本; 1 markdown , -->
              <el-radio v-model="article.editorType" :label="0" @change="editorTypeChange">富文本</el-radio>
              <el-radio v-model="article.editorType" :label="1" @change="editorTypeChange">markdown</el-radio>
              <span style="color: #e6a23c;"> <i class="el-icon-warning-outline" /> 注意!切换编辑器会清空编辑内容</span>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <el-form-item prop="content1">
              <Tinymce v-if="article.editorType===0" ref="tinymce" v-model="article.content1" />
              <mavon-editor v-if="article.editorType===1" ref="movonEditor" v-model="article.content1" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="doAddOrEditArticle">{{ articleId?'立即修改':'立即新增' }}</el-button>
        </el-form-item> -->
      </el-form>
      <el-form ref="form" :rules="rules" label-width="0" :inline="false" size="normal">
        <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <el-form-item prop="content1">
              <Tinymce v-if="article.editorType === 0" ref="tinymce" v-model="article.content1" />
              <mavon-editor v-if="article.editorType === 1" ref="mavonEditor" v-model="article.content1"
                @imgAdd="$imgAdd" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="doAddOrEditArticle">{{ articleId ? '立即修改' : '立即新增' }}</el-button>
        </el-form-item>
      </el-form>

    </el-card>

  </div>
</template>

<script>
import axios from 'axios'
import mix from '@/mixins'
import { getToken } from '@/utils/myAuth'
import { addArticle, productArticle, updateArticle } from '@/api/content/article'
import Tinymce from '@/components/Tinymce'
export default {
  name: 'AddandEditArticle',
  components: {
    Tinymce
  },
  mixins: [mix],
  data() {
    return {
      headtitle: '',
      articleId: null,
      article: {
        editorType: 0
      },
      rules: {
        author: [{ required: true, message: '作者必填', trigger: 'blur' }],
        title: [{ required: true, message: '标题必填', trigger: 'blur' }],
        summary: [{ required: true, message: '摘要必填', trigger: 'blur' }],
        coverImg: [{ required: true, message: '图片必填', trigger: 'blur' }],
        content1: [{ required: true, message: '富文本必填', trigger: 'blur' }]
      }
    }
  },

  created() {
    this.articleId = this.$route.params.id
    this.headtitle = this.$route.meta.title
    if (this.articleId) {
      this.getArticleEdit()
    }
  },

  mounted() {
    console.log(this.$route);
  },

  methods: {

    // 绑定@imgAdd event
    $imgAdd(pos, $file) {
      // 第一步.将图片上传到服务器.
      var formdata = new FormData()
      formdata.append('file', $file)
      axios({
        url: this.uploadFileOss,
        method: 'post',
        data: formdata,
        headers: { 'token': getToken() }
      }).then((res) => {
        // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
        /**
               * $vm 指为mavonEditor实例，可以通过如下两种方式获取
               * 1. 通过引入对象获取: `import {mavonEditor} from ...` 等方式引入后，`$vm`为`mavonEditor`
               * 2. 通过$refs获取: html声明ref : `<mavon-editor ref=md ></mavon-editor>，`$vm`为 `this.$refs.md`
               */
        const { success, data, message } = res.data
        // 判断是否成功
        if (success) {
          this.$refs.mavonEditor.$img2Url(pos, data.fileUrl)
        } else {
          this.$message.error(message)
        }
      })
    },

    // 获取文章
    async getArticleEdit() {
      console.log('----');
      const res = await productArticle(this.articleId)
      const { success, message, data } = res
      // console.log(res)
      if (success) {
        this.article = data.productArticle
      } else {
        this.$message.error(message)
      }
    },

    // 添加文章 与 重新编辑
    doAddOrEditArticle() {
      this.$refs.articleForm.validate(async (valid, object) => {
        if (valid) {
          const editorTypes = this.article.editorType
          if (editorTypes === 0) {
            this.article.content2 = this.article.content1
          } else if (editorTypes === 1) {
            this.article.content2 = this.$refs.movonEditor.d_render
          }
          let api = null
          if (this.articleId) {
            api = updateArticle
          } else {
            api = addArticle
          }
          const res = await api(this.article)
          const { success } = res
          if (success) {
            this.$router.push({ name: 'Articel' })
          }
        }
      })
    },
    // 添加图片
    handleCoverImgSucc(response) {
      // this.$refs.coverImgUplaod.clearFiles()
      const { success, data } = response
      if (success) {
        // 给article里添加实例 利用this.$set完成响应式
        this.$set(this.article, 'coverImg', data.fileUrl)
        this.$message.success('添加成功')
      }
      console.log(response)
    },
    // 判断图片格式大小
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || 'image/png' || 'image/webp'
      const isLtSize = file.size / 1024 / 1024 < 1.5

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG/WEBP 格式!')
      }
      if (!isLtSize) {
        this.$message.error('上传头像图片大小不能超过 1.5MB!')
      }
      return isJPG && isLtSize
    },
    // 当富文本类型改变时
    editorTypeChange() {
      this.article.content1 = ''
    }
  }
}
</script>

<style lang="scss" scoped></style>
